package com.ruoyi.common.upload;

import com.alibaba.fastjson2.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 七牛上传 工具类
 *
 * @author mic-sky
 * @date 2023年9月11日11:28:03
 */

@Component
public class QiniuUtils {

    /**
     * 七牛配置信息
     */
    private static final String ACCESS_KEY = "Hz7g5QOqOrb9TqoOX6zogiMVzLTrernZbKXx8Vw4";
    private static final String SECRET_KEY = "gC8vtbyogA4NEDfD4fvwHig_Vq8anVwcfQ0kZdhY";
    public static final String DOMAIN = "http://img.mel-sm.com";
    private static final String BUCKETNAME = "230325";
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);


    /**
     * 上传
     *
     * @param file
     * @param fileName
     * @return
     */
    public static boolean upload(InputStream file, String fileName) {
        //区域
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            String upToken = auth.uploadToken(BUCKETNAME, fileName);
            Response response = uploadManager.put(file, fileName, upToken, null, null);
            // 解析上传成功的结果
            JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return false;
    }

    /**
     * 删除
     */
    public static boolean del(String fileName) {
        Configuration cfg = new Configuration(Region.huanan());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response delete = bucketManager.delete(BUCKETNAME, fileName);
            return true;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return false;
    }
}
